/**
 * 内容脚本 - 图片视频下载器
 * 负责在网页中检测媒体元素，与后台脚本通信
 */

// 全局变量
let mediaDetector;
let messageHandler;

/**
 * 媒体检测器类
 */
class MediaDetector {
    constructor() {
        this.images = [];
        this.videos = [];
        this.observer = null;
        this.isScanning = false;
    }

    /**
     * 初始化媒体检测器
     */
    init() {
        console.log('初始化媒体检测器...');
        this.scanMedia();
        this.setupObserver();
        this.setupKeyboardShortcuts();
    }

    /**
     * 扫描页面中的媒体元素
     */
    scanMedia() {
        if (this.isScanning) return;
        this.isScanning = true;

        console.log('开始扫描页面媒体...');

        // 扫描图片
        this.scanImages();

        // 扫描视频
        this.scanVideos();

        // 扫描iframe中的媒体
        this.scanIframes();

        this.isScanning = false;
        console.log(`扫描完成: ${this.images.length} 张图片, ${this.videos.length} 个视频`);
    }

    /**
     * 扫描图片元素
     */
    scanImages() {
        const imageSelectors = [
            'img[src]',
            'img[data-src]',
            'img[data-original]',
            'img[data-lazy-src]',
            'img[data-srcset]'
        ];

        imageSelectors.forEach(selector => {
            const images = document.querySelectorAll(selector);
            images.forEach((img, index) => {
                const imageData = this.extractImageData(img, index);
                if (imageData) {
                    this.images.push(imageData);
                }
            });
        });
    }

    /**
     * 提取图片数据
     */
    extractImageData(img, index) {
        let src = img.src || img.dataset.src || img.dataset.original || img.dataset.lazySrc;

        // 处理srcset
        if (img.srcset) {
            const srcset = this.parseSrcset(img.srcset);
            if (srcset.length > 0) {
                // 选择最大尺寸的图片
                src = srcset[srcset.length - 1].url;
            }
        }

        if (!src || !src.startsWith('http')) {
            return null;
        }

        return {
            id: `img_${index}_${Date.now()}`,
            url: src,
            alt: img.alt || '',
            title: img.title || '',
            width: img.naturalWidth || img.width || 0,
            height: img.naturalHeight || img.height || 0,
            filename: this.getFilenameFromUrl(src),
            element: img,
            type: 'image'
        };
    }

    /**
     * 解析srcset属性
     */
    parseSrcset(srcset) {
        const sources = [];
        const parts = srcset.split(',').map(s => s.trim());

        parts.forEach(part => {
            const match = part.match(/^(.+?)(?:\s+(\d+)w)?(?:\s+(\d+)x)?$/);
            if (match) {
                sources.push({
                    url: match[1],
                    width: parseInt(match[2]) || 0,
                    density: parseFloat(match[3]) || 1
                });
            }
        });

        return sources.sort((a, b) => a.width - b.width);
    }

    /**
     * 扫描视频元素
     */
    scanVideos() {
        const videoSelectors = [
            'video',
            'video source',
            'iframe[src*="video"]',
            'iframe[src*="youtube"]',
            'iframe[src*="vimeo"]',
            'iframe[src*="dailymotion"]',
            'iframe[src*="bilibili"]'
        ];

        videoSelectors.forEach(selector => {
            const videos = document.querySelectorAll(selector);
            videos.forEach((video, index) => {
                const videoData = this.extractVideoData(video, index);
                if (videoData) {
                    this.videos.push(videoData);
                }
            });
        });
    }

    /**
     * 提取视频数据
     */
    extractVideoData(video, index) {
        let src = video.src;
        let title = video.title || '';

        // 处理video标签
        if (video.tagName.toLowerCase() === 'video') {
            if (video.querySelector('source')) {
                const source = video.querySelector('source');
                src = source.src || source.dataset.src;
            }
            title = title || video.dataset.title || '';
        }

        // 处理iframe
        else if (video.tagName.toLowerCase() === 'iframe') {
            src = video.src;
            title = title || video.dataset.title || video.alt || '';
        }

        if (!src || !src.startsWith('http')) {
            return null;
        }

        return {
            id: `video_${index}_${Date.now()}`,
            url: src,
            title: title,
            width: video.videoWidth || video.width || 0,
            height: video.videoHeight || video.height || 0,
            duration: video.duration || 0,
            filename: this.getFilenameFromUrl(src),
            element: video,
            type: 'video'
        };
    }

    /**
     * 扫描iframe中的媒体
     */
    scanIframes() {
        const iframes = document.querySelectorAll('iframe');
        iframes.forEach(iframe => {
            try {
                // 尝试访问iframe内容（同源）
                if (iframe.contentDocument) {
                    const iframeImages = iframe.contentDocument.querySelectorAll('img[src]');
                    const iframeVideos = iframe.contentDocument.querySelectorAll('video');

                    iframeImages.forEach((img, index) => {
                        const imageData = this.extractImageData(img, `iframe_img_${index}`);
                        if (imageData) {
                            this.images.push(imageData);
                        }
                    });

                    iframeVideos.forEach((video, index) => {
                        const videoData = this.extractVideoData(video, `iframe_video_${index}`);
                        if (videoData) {
                            this.videos.push(videoData);
                        }
                    });
                }
            } catch (error) {
                // 跨域iframe无法访问，忽略错误
                console.log('无法访问iframe内容（跨域限制）');
            }
        });
    }

    /**
     * 设置DOM观察器
     */
    setupObserver() {
        this.observer = new MutationObserver((mutations) => {
            let hasNewMedia = false;

            mutations.forEach(mutation => {
                if (mutation.type === 'childList') {
                    mutation.addedNodes.forEach(node => {
                        if (node.nodeType === Node.ELEMENT_NODE) {
                            if (node.matches && (node.matches('img, video, iframe') ||
                                node.querySelector('img, video, iframe'))) {
                                hasNewMedia = true;
                            }
                        }
                    });
                }
            });

            if (hasNewMedia) {
                // 延迟扫描，避免频繁触发
                setTimeout(() => {
                    this.scanMedia();
                }, 1000);
            }
        });

        this.observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    }

    /**
     * 设置键盘快捷键
     */
    setupKeyboardShortcuts() {
        document.addEventListener('keydown', (event) => {
            // Ctrl+Shift+D: 扫描媒体
            if (event.ctrlKey && event.shiftKey && event.key === 'D') {
                event.preventDefault();
                this.scanMedia();
                this.notifyBackground('mediaScanned', {
                    images: this.images,
                    videos: this.videos
                });
            }
        });
    }

    /**
     * 从URL中提取文件名
     */
    getFilenameFromUrl(url) {
        try {
            const urlObj = new URL(url);
            const pathname = urlObj.pathname;
            const filename = pathname.split('/').pop();

            // 如果没有扩展名，尝试添加
            if (filename && !filename.includes('.')) {
                const contentType = this.getContentTypeFromUrl(url);
                if (contentType) {
                    return `${filename}.${contentType}`;
                }
            }

            return filename || 'unknown';
        } catch (error) {
            return 'unknown';
        }
    }

    /**
     * 从URL推断内容类型
     */
    getContentTypeFromUrl(url) {
        if (url.includes('image/')) return 'jpg';
        if (url.includes('video/')) return 'mp4';
        return null;
    }

    /**
     * 通知后台脚本
     */
    notifyBackground(action, data) {
        chrome.runtime.sendMessage({
            action: action,
            data: data,
            tabId: window.location.href
        }).catch(error => {
            console.log('无法发送消息到后台脚本:', error);
        });
    }

    /**
     * 获取所有媒体数据
     */
    getAllMedia() {
        return {
            images: this.images,
            videos: this.videos,
            timestamp: Date.now(),
            url: window.location.href,
            title: document.title
        };
    }

    /**
     * 清理资源
     */
    destroy() {
        if (this.observer) {
            this.observer.disconnect();
        }
    }
}

/**
 * 消息处理器类
 */
class MessageHandler {
    constructor(mediaDetector) {
        this.mediaDetector = mediaDetector;
        this.setupMessageListener();
    }

    /**
     * 设置消息监听器
     */
    setupMessageListener() {
        chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
            console.log('内容脚本收到消息:', request);

            switch (request.action) {
                case 'scanMedia':
                    this.handleScanMedia(sendResponse);
                    break;
                case 'getMediaData':
                    this.handleGetMediaData(sendResponse);
                    break;
                case 'highlightElement':
                    this.handleHighlightElement(request, sendResponse);
                    break;
                default:
                    sendResponse({ success: false, error: '未知操作' });
            }

            return true; // 异步响应
        });
    }

    /**
     * 处理扫描媒体请求
     */
    handleScanMedia(sendResponse) {
        try {
            this.mediaDetector.scanMedia();
            const mediaData = this.mediaDetector.getAllMedia();
            sendResponse({ success: true, data: mediaData });
        } catch (error) {
            console.error('扫描媒体失败:', error);
            sendResponse({ success: false, error: error.message });
        }
    }

    /**
     * 处理获取媒体数据请求
     */
    handleGetMediaData(sendResponse) {
        try {
            const mediaData = this.mediaDetector.getAllMedia();
            sendResponse({ success: true, data: mediaData });
        } catch (error) {
            console.error('获取媒体数据失败:', error);
            sendResponse({ success: false, error: error.message });
        }
    }

    /**
     * 处理高亮元素请求
     */
    handleHighlightElement(request, sendResponse) {
        try {
            const { elementId, type } = request;
            const element = document.querySelector(`[data-media-id="${elementId}"]`);

            if (element) {
                this.highlightElement(element);
                sendResponse({ success: true });
            } else {
                sendResponse({ success: false, error: '元素未找到' });
            }
        } catch (error) {
            console.error('高亮元素失败:', error);
            sendResponse({ success: false, error: error.message });
        }
    }

    /**
     * 高亮元素
     */
    highlightElement(element) {
        // 移除之前的高亮
        document.querySelectorAll('.media-highlight').forEach(el => {
            el.classList.remove('media-highlight');
        });

        // 添加高亮
        element.classList.add('media-highlight');

        // 滚动到元素位置
        element.scrollIntoView({ behavior: 'smooth', block: 'center' });

        // 3秒后移除高亮
        setTimeout(() => {
            element.classList.remove('media-highlight');
        }, 3000);
    }
}

/**
 * 初始化内容脚本
 */
function initializeContentScript() {
    console.log('初始化内容脚本...');

    // 等待DOM加载完成
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            startContentScript();
        });
    } else {
        startContentScript();
    }
}

/**
 * 启动内容脚本
 */
function startContentScript() {
    // 创建媒体检测器
    mediaDetector = new MediaDetector();
    mediaDetector.init();

    // 创建消息处理器
    messageHandler = new MessageHandler(mediaDetector);

    // 添加高亮样式
    addHighlightStyles();

    console.log('内容脚本启动完成');
}

/**
 * 添加高亮样式
 */
function addHighlightStyles() {
    const style = document.createElement('style');
    style.textContent = `
    .media-highlight {
      outline: 3px solid #2196F3 !important;
      outline-offset: 2px !important;
      animation: media-pulse 1s ease-in-out infinite alternate !important;
    }
    
    @keyframes media-pulse {
      from { outline-color: #2196F3; }
      to { outline-color: #1976D2; }
    }
  `;
    document.head.appendChild(style);
}

/**
 * 页面卸载时清理资源
 */
window.addEventListener('beforeunload', () => {
    if (mediaDetector) {
        mediaDetector.destroy();
    }
});

// 启动内容脚本
initializeContentScript(); 